<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-left">
        <img src="@/assets/images/register-bg.jpg" alt="旅游风景" />
      </div>
      <div class="register-right">
        <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
          <h3 class="title">用户注册</h3>

          <el-form-item prop="mobile">
            <el-input v-model="registerForm.mobile" placeholder="手机号">
              <i slot="prefix" class="el-input__icon el-icon-mobile-phone"></i>
              <el-button slot="append" @click="handleSendCode" :disabled="isCodeSending" class="code-btn">
                {{ codeBtnText }}
              </el-button>
            </el-input>
          </el-form-item>

          <el-form-item prop="code">
            <el-input v-model="registerForm.code" placeholder="验证码">
              <i slot="prefix" class="el-input__icon el-icon-message"></i>
            </el-input>
          </el-form-item>

          <el-form-item prop="password">
            <el-input v-model="registerForm.password" type="password" placeholder="密码">
              <i slot="prefix" class="el-input__icon el-icon-lock"></i>
            </el-input>
          </el-form-item>

          <el-button :loading="loading" type="primary" class="register-btn" @click.native.prevent="handleRegister">
            注册
          </el-button>

          <div class="tips">
            <span>已有账号？</span>
            <router-link to="/login" class="login-link">立即登录</router-link>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 信息完善弹窗 -->
    <el-dialog
        title="完善个人信息"
        :visible.sync="completeDialogVisible"
        :close-on-click-modal="false"
        width="500px"
        class="complete-dialog"
        :show-close="false"
    >
      <div class="dialog-content">
        <div class="welcome-text">欢迎加入长隆旅游社！</div>
        <div class="sub-text">请完善您的个人信息，让我们更好地为您服务</div>

        <el-form ref="completeForm" :model="completeForm" :rules="completeRules" label-width="80px">
          <el-form-item prop="nickname" label="昵称">
            <el-input
                v-model="completeForm.nickname"
                placeholder="请输入昵称"
                prefix-icon="el-icon-user"
            />
          </el-form-item>

          <el-form-item prop="email" label="邮箱">
            <el-input
                v-model="completeForm.email"
                placeholder="请输入邮箱"
                prefix-icon="el-icon-message"
            />
          </el-form-item>

          <el-form-item prop="gender" label="性别">
            <el-radio-group v-model="completeForm.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item prop="birthday" label="生日">
            <el-date-picker
                v-model="completeForm.birthday"
                type="date"
                placeholder="选择生日"
                style="width: 100%"
                value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item prop="realName" label="真实姓名">
            <el-input
                v-model="completeForm.realName"
                placeholder="请输入真实姓名（选填）"
                prefix-icon="el-icon-user"
            />
          </el-form-item>
        </el-form>

        <div class="dialog-footer">
          <el-button @click="skipComplete" plain>暂不完善</el-button>
          <el-button type="primary" @click="handleComplete" :loading="submitLoading">
            确认提交
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sendCode, register, completeInfo, checkUser } from '@/api/user'

export default {
  name: 'Register',
  data() {
    return {
      registerForm: {
        mobile: '',
        code: '',
        password: ''
      },
      completeForm: {
        nickname: '',
        email: '',
        gender: '',
        birthday: '',
        realName: ''
      },
      registerRules: {
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
        ]
      },
      completeRules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请选择生日', trigger: 'change' }
        ]
      },
      loading: false,
      isCodeSending: false,
      countdown: 60,
      timer: null,
      completeDialogVisible: false,
      userId: null,
      submitLoading: false
    }
  },
  computed: {
    codeBtnText() {
      return this.isCodeSending ? `${this.countdown}s后重试` : '获取验证码'
    }
  },
  methods: {
    async handleSendCode() {
      if (this.isCodeSending) return

      // 验证手机号
      if (!this.registerForm.mobile) {
        this.$message.error('请输入手机号')
        return
      }

      try {
        // 使用 api 中定义的 sendCode 方法
        const res = await sendCode(this.registerForm.mobile)
        if (res.code === 200) {
          // 开始倒计时
          this.isCodeSending = true
          this.countdown = 60
          this.timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--
            } else {
              this.isCodeSending = false
              clearInterval(this.timer)
            }
          }, 1000)

          this.$message.success('验证码已发送')
        } else {
          this.$message.error(res.message || '发送验证码失败')
        }
      } catch (error) {
        this.$message.error(error.message || '发送验证码失败')
      }
    },
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          this.isCodeSending = false
          this.countdown = 60
          clearInterval(this.timer)
        }
      }, 1000)
    },
    async handleRegister() {
      try {
        await this.$refs.registerForm.validate()
        this.loading = true
        const registerData = {
          mobile: this.registerForm.mobile,
          code: this.registerForm.code,
          password: this.registerForm.password
        }
        const res = await register(registerData)
        if (res.code === 200) {
          this.userId = res.data.userId
          // 存储token
          this.$store.commit('SET_TOKEN', res.data.token)

          // 先显示成功消息
          this.$message.success('注册成功')

          // 延迟显示完善信息弹窗
          setTimeout(() => {
            this.completeDialogVisible = true
          }, 1000)

          // 跳转到首页
          this.$router.push({ path: '/', query: { needComplete: true } })
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loading = false
      }
    },
    async handleComplete() {
      try {
        await this.$refs.completeForm.validate()
        this.submitLoading = true
        const res = await completeInfo(this.userId, this.completeForm)
        if (res.code === 200) {
          this.$message.success('信息完善成功')
          this.completeDialogVisible = false
        } else {
          this.$message.error(res.message)
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.submitLoading = false
      }
    },
    skipComplete() {
      this.completeDialogVisible = false
      this.$message.info('您可以稍后在个人中心完善信息')
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="scss" scoped>
.register-container {
  min-height: 100vh;
  width: 100%;
  background-image: linear-gradient(to right, #24243e, #302b63, #0f0c29);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;

  .register-box {
    width: 1000px;
    height: 600px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 10px;
    box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
    display: flex;
    overflow: hidden;
    animation: fadeIn 0.5s ease-out;

    .register-left {
      flex: 1;
      overflow: hidden;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s;

        &:hover {
          transform: scale(1.05);
        }
      }
    }

    .register-right {
      flex: 1;
      padding: 40px;
      display: flex;
      align-items: center;
      background: rgba(255, 255, 255, 0.95);
    }
  }

  .register-form {
    width: 100%;
    padding: 0 20px;

    .title {
      font-size: 26px;
      color: #302b63;
      margin: 0 auto 40px auto;
      text-align: center;
      font-weight: bold;
      letter-spacing: 2px;
    }

    .el-input {
      background: transparent;

      ::v-deep input {
        height: 48px;
        line-height: 48px;
        background: #f5f7fa;
        border: none;
        border-radius: 24px;
        color: #606266;
        padding-left: 45px;

        &:focus {
          background: #fff;
          box-shadow: 0 0 10px rgba(48, 43, 99, 0.1);
        }
      }

      ::v-deep .el-input__prefix {
        left: 16px;
        color: #909399;
      }

      ::v-deep .el-input-group__append {
        background: transparent;
        border: none;
        padding: 0 5px;
      }

      .code-btn {
        height: 40px;
        border-radius: 20px;
        padding: 0 15px;
        background: linear-gradient(to right, #24243e, #302b63);
        border: none;
        color: #fff;

        &:hover:not(:disabled) {
          background: linear-gradient(to right, #302b63, #24243e);
        }

        &:disabled {
          background: #909399;
          color: #fff;
        }
      }
    }

    .register-btn {
      width: 100%;
      height: 48px;
      border-radius: 24px;
      font-size: 16px;
      margin-top: 10px;
      background: linear-gradient(to right, #24243e, #302b63);
      border: none;

      &:hover {
        background: linear-gradient(to right, #302b63, #24243e);
      }
    }

    .tips {
      font-size: 14px;
      color: #606266;
      margin-top: 20px;
      text-align: center;

      .login-link {
        color: #302b63;
        margin-left: 8px;
        text-decoration: none;
        font-weight: bold;

        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}

.complete-dialog {
  ::v-deep .el-dialog {
    border-radius: 8px;
    overflow: hidden;

    .el-dialog__header {
      padding: 20px;
      background: linear-gradient(to right, #24243e, #302b63);
      margin-right: 0;

      .el-dialog__title {
        color: #fff;
        font-size: 18px;
        font-weight: 500;
      }
    }

    .el-dialog__body {
      padding: 30px;
    }
  }

  .dialog-content {
    .welcome-text {
      font-size: 24px;
      color: #302b63;
      text-align: center;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .sub-text {
      font-size: 14px;
      color: #909399;
      text-align: center;
      margin-bottom: 30px;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 20px;

        ::v-deep .el-input__inner {
          height: 40px;
          line-height: 40px;
          border-radius: 4px;
        }

        ::v-deep .el-radio {
          margin-right: 30px;
        }
      }
    }

    .dialog-footer {
      text-align: center;
      margin-top: 30px;

      .el-button {
        width: 120px;
        height: 40px;
        border-radius: 20px;
        font-size: 14px;

        &.el-button--primary {
          background: linear-gradient(to right, #24243e, #302b63);
          border: none;
          margin-left: 20px;

          &:hover {
            background: linear-gradient(to right, #302b63, #24243e);
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
